import { defineComponent } from 'vue'
import { FiledPropsDefine } from '../types'
import { useSchemaFormContext } from '../context'
import SchemaItem from '../SchemaItem'
import { isObject } from '../utils'

export default defineComponent({
  name: 'ObjectField',
  props: FiledPropsDefine,
  setup(props) {
    const context = useSchemaFormContext()

    const handleChange = (key: string, v: string) => {
      const value: any = isObject(props.value) ? props.value : {}

      if (v === undefined) {
        delete value[key]
      } else {
        value[key] = v
      }

      props.onChange(value)
    }

    return () => {
      const { schema, value, rootSchema } = props

      const { properties = {} } = schema

      const { SchemaItem } = context

      const currentValue: any = isObject(value) ? value : {}

      return Object.keys(properties).map((item, index) => (
        <SchemaItem
          schema={properties[item]}
          rootSchema={rootSchema}
          value={currentValue[item]}
          key={index}
          onChange={(v: any) => handleChange(item, v)}
        />
      ))
    }
  },
})
